package cn.net.autocode.core.utils;

import com.alibaba.fastjson2.JSONObject;

/**
 * 线程中存储用户信息
 **/
public class UserThreadLocalUtils {

    private static final ThreadLocal<JSONObject> LOCAL = new ThreadLocal<>();
    private static final ThreadLocal<String> CLIENT_IP= new ThreadLocal<>();

    private static final ThreadLocal<String> TOKEN = new ThreadLocal<>();

    public static void put(JSONObject sysUser) {
        LOCAL.set(sysUser);
    }

    public static JSONObject get() {
        return LOCAL.get();
    }

    /**
     * 获取登录账号
     */
    public static String getUserName() {
        JSONObject userInfo = LOCAL.get();
        return userInfo.getString("username");
    }

    public static void setDefaultInfo(String orgCode,String userName){
        JSONObject json = LOCAL.get();
        if (json == null || json.isEmpty()) {
            json = new JSONObject();
            json.put("username", userName);
            json.put("orgCode", orgCode);
            LOCAL.set(json);
        }else{
            json.put("username", userName);
            json.put("orgCode", orgCode);
            LOCAL.set(json);
        }
    }


    /**
     * 获取真实姓名
     *
     */
    public static String getRealName() {
        JSONObject userInfo = LOCAL.get();
        return userInfo.getString("fullname");
    }

    /**
     * 获取组织机构代码
     *
     */
    public static String getOrgCode() {
        JSONObject userInfo = LOCAL.get();
        return userInfo.getString("orgCode");
    }

    public static String getOrgName() {
        JSONObject userInfo = LOCAL.get();
        return userInfo.getString("orgName");
    }

    public static String getEmail() {
        JSONObject userInfo = LOCAL.get();
        return userInfo.getString("email");
    }

    public static String getPhone() {
        JSONObject userInfo = LOCAL.get();
        return userInfo.getString("phone");
    }


    public static void setClientIp(String ip) {
        CLIENT_IP.set(ip);
    }

    public static String getClientIp() {
        return CLIENT_IP.get();
    }

    public static void setToken(String token) {
        TOKEN.set(token);
    }

    public static String getToken() {
        return TOKEN.get();
    }

    public static boolean checkPassword(String password) {
        JSONObject userInfo = LOCAL.get();
        if (userInfo == null) {
            return false;
        }
        return PasswordUtils.checkpw(password, userInfo.getString("passwrd"));
    }

    public static void clear() {
       LOCAL.remove();
       CLIENT_IP.remove();
       TOKEN.remove();
    }

}
